package com.marver.login.service;

import com.marver.beans.request.GetTokenReq;
import com.marver.beans.request.LoginReq;
import com.marver.beans.response.AccessToken;
import com.marver.beans.response.UserProductDto;
import com.marver.common.Audience;
import com.marver.common.dao.BaseDAOImpl;
import com.marver.common.result.Result;
import com.marver.common.result.ResultStatus;
import com.marver.common.utils.JedisUtils;
import com.marver.common.utils.JwtHelper;
import com.marver.common.utils.MD5Util;
import com.marver.entity.AdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class LoginService extends BaseDAOImpl {
    @Autowired  
    private Audience audienceEntity;
	public Result getLoginToken(LoginReq qo, String remoteIp, boolean isAdminLogin)
    {  
        Result resultMsg=new Result();
        //验证码校验  
		String captchaCode = qo.getCaptchaCode();
	    if (captchaCode == null)  
	    {  
	    	resultMsg.setCode(ResultStatus.INVALID_PARAM.getErrorCode());
			resultMsg.getMsg().setTip("验证码编号为空，请与管理员联系！");
			return resultMsg;
	    } 
	    
	    String captchaValue = JedisUtils.get(captchaCode);
	    if (captchaValue == null)  
	    {  
	    	resultMsg.setCode(ResultStatus.INVALID_PARAM.getErrorCode());
			resultMsg.getMsg().setTip("验证码无效，请重新获取！");
			return resultMsg;
		}
	    if (!captchaValue.toLowerCase().equals(qo.getCaptchaValue().toLowerCase())){
	    	resultMsg.setCode(ResultStatus.INVALID_PARAM.getErrorCode());
			resultMsg.getMsg().setTip("验证码错误，请重新输入！");
			return resultMsg;
	    } 
 
        //验证用户名密码
        AdminUser user = (AdminUser)this.findObjectBySqlMap("account.checkLoginAccount", qo);
        if (user == null)  
        {  
            resultMsg = new Result(ResultStatus.FAIL.getErrorCodeToString(),"用户名不存在");
            return resultMsg;  
        }  
        else  
        {
            String md5Password = MD5Util.createMD5Util().getMD5String(qo.getPassword());
            if (!md5Password.toUpperCase().equals(user.getPassword().toUpperCase()))  
            {  
                resultMsg = new Result(ResultStatus.FAIL.getErrorCodeToString(),"密码错误");  
                return resultMsg;  
            }  
        }  
        
        //有效时长，默认2小时，用户可自行设置，但最长10小时。
        long expiresSecond=audienceEntity.getExpiresSecond();
        if (qo.getExpiresTime()>0){
        	expiresSecond=qo.getExpiresTime();
        	if(expiresSecond>36000){
        		expiresSecond=36000;
        	}
        }
        
        //拼装accessToken  
        String accessToken = JwtHelper.createJWT(remoteIp,qo.getUserNum(), String.valueOf(user.getId()), user.getUsername(),
        		expiresSecond*1000, audienceEntity.getBase64Secret(),"");

        //返回accessToken  
        AccessToken accessTokenEntity = new AccessToken();  
        accessTokenEntity.setAccessToken(accessToken);
        accessTokenEntity.setExpiresIn(expiresSecond);
        accessTokenEntity.setTokenType("bearer");
        List<AccessToken> list=new ArrayList<AccessToken>();
        list.add(accessTokenEntity);
        resultMsg = new Result(ResultStatus.SUCCESS.getErrorCode(),list);  
        
        //删除redis保存的图片验证码，确保一个验证码仅可正确使用一次
        JedisUtils.del(captchaCode);
        return resultMsg;  

    }

    /**
     * 获取认证token
     * @param qo
     * @param remoteIp
     * @return
     */
    public Result getAccessToken(GetTokenReq qo, String remoteIp) {
        Result resultMsg;
        //验证用户
        UserProductDto userDto = (UserProductDto)this.findObjectBySqlMap("account.queryUserProduct", qo);
        if (userDto == null){
            resultMsg = new Result(ResultStatus.FAIL.getErrorCodeToString(),"用户名不存在");
            return resultMsg;
        }
        //有效时长，默认2小时
        long expiresSecond=audienceEntity.getExpiresSecond();

        //拼装accessToken
        String accessToken = JwtHelper.createJWT(remoteIp,userDto.getAppId(), String.valueOf(userDto.getUserId()),userDto.getUserNum(),
                            expiresSecond*1000, audienceEntity.getBase64Secret(),userDto.getAuthCode());

        //返回accessToken
        AccessToken accessTokenEntity = new AccessToken();
        accessTokenEntity.setAccessToken(accessToken);
        accessTokenEntity.setExpiresIn(expiresSecond);
        accessTokenEntity.setTokenType("bearer");
        resultMsg = new Result(ResultStatus.SUCCESS.getErrorCode(),accessTokenEntity);
        return resultMsg;
    }
}

